package com.tk.exam.utils;

import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;

@Slf4j
public class MD5Utils {
	private static final char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
	
	public static String MD5(String key) {
		try {
		    key = new String(key.getBytes("UTF-8"));
			byte[] bytes = key.getBytes();
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            md.update(bytes);
            // 获得密文
            byte[] byteMd = md.digest();
            // 把密文转换成十六进制的字符串形式
            int j = byteMd.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte bt = byteMd[i];
                str[k++] = hexDigits[bt >>> 4 & 0xf];
                str[k++] = hexDigits[bt & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            throw new RuntimeException();
        }
	}
}
